<template>
	<view class="create-team">
		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 球队Logo上传 -->
			<view class="form-item">
				<view class="logo-upload" @tap="uploadLogo">
					<image v-if="formData.logo" :src="formData.coverImage" mode="aspectFill" class="logo-preview">
					</image>
					<view v-else class="upload-placeholder">
						<view class="upload-content">
							<text class="icon">+</text>
							<text class="text">上传球队Logo</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 球队名称 -->
			<view class="form-item">
				<view class="input-row">
					<text class="label">球队名称</text>
					<view class="input-wrapper">
						<input type="text" v-model="formData.name" placeholder="请输入球队名称" maxlength="20" />
					</view>
				</view>
			</view>

			<!-- 球队口号 -->
			<view class="form-item">
				<view class="input-row">
					<text class="label">球队口号</text>
					<view class="input-wrapper">
						<input type="text" v-model="formData.slogan" placeholder="请输入球队口号" maxlength="30" />
					</view>
				</view>
			</view>

			<!-- 所在地区 -->
			<view class="form-item">
				<text class="label">所在地区</text>
				<view class="area-picker">
					<picker :range="currentArea.provinces" range-key="areaName" :value="areaIndex[0]"
						@change="onProvinceChange">
						<view class="picker-item">
							<text>{{ areaNameIndex[0] || '选择省份' }}</text>
						</view>
					</picker>
					<picker :range="currentArea.cities" range-key="areaName" :value="areaIndex[1]"
						@change="onCityChange">
						<view class="picker-item">
							<text>{{ areaNameIndex[1] || '选择城市' }}</text>
						</view>
					</picker>
					<picker :range="currentArea.districts" range-key="areaName" :value="areaIndex[2]"
						@change="onDistrictChange">
						<view class="picker-item">
							<text>{{ areaNameIndex[2] || '选择区域' }}</text>
						</view>
					</picker>
				</view>
			</view>

			<!-- 球队详细地址 -->
			<view class="form-item">
				<text class="label">球队详细地址</text>
				<textarea v-model="formData.address" placeholder="请输入球队简介" maxlength="200" />
				<text class="word-count">{{ formData.address.length }}/200</text>
			</view>

			<!-- 球队简介 -->
			<view class="form-item">
				<text class="label">球队简介</text>
				<textarea v-model="formData.description" placeholder="请输入球队简介" maxlength="200" />
				<text class="word-count">{{ formData.description.length }}/200</text>
			</view>


			<!-- 加入方式 -->
			<view class="form-item">
				<text class="label">加入方式</text>
				<radio-group @change="onJoinTypeChange">
					<label v-for="(type, index) in joinTypes" :key="index" class="radio-label">
						<radio :value="type.value" :checked="formData.joinType === type.value" />
						<text>{{ type.label }}</text>
					</label>
				</radio-group>
			</view>

			<!-- 球队标签 -->
			<view class="form-item">
				<text class="label">球队标签</text>
				<view class="tags-container">
					<view v-for="(tag, index) in tags" :key="index" class="tag"
						:class="{ active: selectedTags.includes(tag) }" @tap="toggleTag(tag)">
						{{ tag }}
					</view>
				</view>
			</view>

			<!-- 平台展示设置 -->
			<view class="form-item switch-item">
				<text class="label">是否在平台展示</text>
				<switch :checked="formData.isPublic" @change="onPublicChange" color="#4CAF50" />
			</view>
		</view>

		<!-- 创建按钮 -->
		<view class="bottom-actions">
			<button class="create-btn" @tap="updateTeams()">提交更新</button>
		</view>
	</view>
</template>

<script>
	import {
		updateTeams,
		uploadCover,
		getTeams
	} from '@/api/youqiu/team.js'
	import {
		listAreaByCode
	} from '@/api/common/area.js'

	export default {
		data() {
			return {
				formData: {
					ossId: 0,
					logo: '',
					coverImage: '',
					name: '',
					slogan: '',
					region: {
						province: '',
						city: '',
						district: ''
					},
					description: '',
					joinType: 'verify',
					tags: [],
					isPublic: true,
					address: ''
				},
				joinTypes: [
					/* {
						label: '需要审核',
						value: 'verify'
					},
					{
						label: '自由加入',
						value: 'free'
					}, */
					{
						label: '仅邀请',
						value: 'invite'
					}
				],
				tags: ['足球', '11制', '8人制', '5人制', '周末活动', '工作日活动', '竞技', '休闲'],
				selectedTags: [],
				currentArea: {
					provinces: [],
					cities: [],
					districts: []
				},
				areaIndex: [0, 0, 0],
				areaNameIndex: ['', '', ''],
				teamId: 0,
				teamInfo: null,
			}
		},
		onLoad(options) {
			if (options.teamId) {
				this.teamId = options.teamId
				this.getTeamDetails()
			}
		},
		watch: {
			teamInfo: {
				immediate: true,
				async handler(newVal) {
					if (!newVal) return

					await this.listProvince()

					if (newVal.province) {
						const provinceIndex = this.currentArea.provinces.findIndex(
							province => province.areaCode === newVal.province
						)

						if (provinceIndex !== -1) {
							this.areaIndex[0] = provinceIndex
							this.areaNameIndex[0] = this.currentArea.provinces[provinceIndex].areaName

							await this.listCity(newVal.province)

							if (newVal.city) {
								const cityIndex = this.currentArea.cities.findIndex(
									city => city.areaCode === newVal.city
								)

								if (cityIndex !== -1) {
									this.areaIndex[1] = cityIndex
									this.areaNameIndex[1] = this.currentArea.cities[cityIndex].areaName

									await this.listDistrict(newVal.city)

									if (newVal.district) {
										const districtIndex = this.currentArea.districts.findIndex(
											district => district.areaCode === newVal.district
										)

										if (districtIndex !== -1) {
											this.areaIndex[2] = districtIndex
											this.areaNameIndex[2] = this.currentArea.districts[districtIndex].areaName
										}
									}
								}
							}
						}
					}
				}
			}
		},
		methods: {
			async listProvince() {
				let param = {
					areaParent: '0'
				}
				try {
					const res = await listAreaByCode(param)
					console.log('listProvince', res)
					this.currentArea.provinces = res.data
				} catch (err) {
					console.error('获取省份列表失败:', err)
				}
			},
			async listCity(areaCode) {
				let param = {
					areaParent: areaCode
				}
				try {
					const res = await listAreaByCode(param)
					console.log('listCity', res)
					this.currentArea.cities = res.data
				} catch (err) {
					console.error('获取城市列表失败:', err)
				}
			},
			async listDistrict(areaCode) {
				let param = {
					areaParent: areaCode
				}
				try {
					const res = await listAreaByCode(param)
					console.log('listDistrict', res)
					this.currentArea.districts = res.data
				} catch (err) {
					console.error('获取区域列表失败:', err)
				}
			},
			// 获取球队详情
			getTeamDetails() {
				let _this = this
				getTeams(this.teamId).then(res => {
					if (res.code === 200) {
						this.teamInfo = res.data
						// 回填表单数据
						_this.formData = {
							id: this.teamId,
							name: res.data.name,
							description: res.data.description,
							logo: res.data.logo,
							coverImage: res.data.coverImage,
							province: res.data.province,
							city: res.data.city,
							district: res.data.district,
							address: res.data.address,
							joinType: res.data.joinType || 'apply',
							tags: res.data.tags || '',
							region: {
								province: res.data.province || '',
								city: res.data.city || '',
								district: res.data.district || ''
							}
						}

						// 回填标签到选中状态
						if (res.data.tags) {
							this.selectedTags = res.data.tags.split(',').map(tag => tag.trim())
						}
					}
				})
			},
			// 上传Logo
			uploadLogo() {
				let _this = this
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						this.formData.coverImage = tempFilePath
						this.formData.logo = tempFilePath
						// TODO: 上传图片到服务器
						let data = {
							name: 'file',
							filePath: tempFilePath
						}
						uploadCover(data).then(response => {
							//store.commit('SET_AVATAR', baseUrl + response.imgUrl)
							console.log('uploadCover', response)
							uni.showToast({
								title: "上传成功",
								icon: 'success'
							})
							_this.formData.coverImage = response.data.url
							_this.formData.logo = response.data.url
							_this.formData.ossId = response.data.ossId
						})
					}
				})
			},

			// 处理省份变化
			onProvinceChange(e) {
				if (!this.currentArea.provinces || !this.currentArea.provinces.length) {
					return
				}

				const provinceIndex = e.detail.value
				console.log(e.detail.value)
				this.areaIndex[0] = provinceIndex
				this.areaNameIndex[0] = this.currentArea.provinces[provinceIndex].areaName

				// 更新城市列表
				let param = {
					areaParent: this.currentArea.provinces[provinceIndex].areaCode
				}
				let _this = this
				listAreaByCode(param).then(res => {
					console.log('listAreaByCode Province', res)
					_this.currentArea.cities = res.data
				})

				// 重置城市和区域索引
				this.areaIndex[1] = 0
				this.areaIndex[2] = 0
				this.areaNameIndex[1] = ''
				this.areaNameIndex[2] = ''

				const selectedProvince = this.currentArea.provinces[this.areaIndex[0]].areaCode
				this.formData.province = selectedProvince
			},

			// 处理城市变化
			onCityChange(e) {
				if (!this.currentArea.cities || !this.currentArea.cities.length) {
					return
				}

				if (this.currentArea.cities && this.currentArea.cities.length > 0) {
					const cityIndex = e.detail.value
					this.areaIndex[1] = cityIndex
					this.areaNameIndex[1] = this.currentArea.cities[cityIndex].areaName

					// 更新区域列表
					let param = {
						areaParent: this.currentArea.cities[cityIndex].areaCode
					}
					let _this = this
					listAreaByCode(param).then(res => {
						console.log('listAreaByCode city', res)
						_this.currentArea.districts = res.data
					})

					this.areaIndex[2] = 0
					this.areaNameIndex[2] = ''
					this.formData.city = this.currentArea.cities[cityIndex].areaCode
				}
			},

			// 处理区域变化
			onDistrictChange(e) {
				if (!this.currentArea.districts || !this.currentArea.districts.length) {
					return
				}

				console.log('onDistrictChange', e)
				console.log('onDistrictChange', this.currentArea.districts)
				if (this.currentArea.districts && this.currentArea.districts.length > 0) {
					this.areaIndex[2] = e.detail.value
					this.areaNameIndex[2] = this.currentArea.districts[this.areaIndex[2]].areaName
					this.formData.district = this.currentArea.districts[this.areaIndex[2]].areaCode
				}
			},

			// 加入方式选择
			onJoinTypeChange(e) {
				this.formData.joinType = e.detail.value
			},

			// 标签选择
			toggleTag(tag) {
				const index = this.selectedTags.indexOf(tag)
				if (index > -1) {
					this.selectedTags.splice(index, 1)
				} else if (this.selectedTags.length < 3) {
					this.selectedTags.push(tag)
				} else {
					uni.showToast({
						title: '最多选择3个标签',
						icon: 'none'
					})
				}
				this.formData.tags = this.selectedTags.join(',')
			},

			// 更新球队
			async updateTeams() {
				if (!this.formData.name) {
					uni.showToast({
						title: '请输入球队名称',
						icon: 'none'
					})
					return
				}

				if (!this.formData.region.province) {
					uni.showToast({
						title: '请选择所在地区',
						icon: 'none'
					})
					return
				}

				try {
					const response = await updateTeams(this.formData)
					if (response.code === 200) {
						uni.showToast({
							title: '更新成功',
							icon: 'success'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}
				} catch (error) {
					console.error('更新球队失败:', error)
					uni.showToast({
						title: '更新失败',
						icon: 'none'
					})
				}
			},

			onPublicChange(e) {
				this.formData.isPublic = e.detail.value
			}
		}
	}
</script>

<style lang="scss" scoped>
	.create-team {
		min-height: 100vh;
		background-color: #f8f8f8;
		padding: 20rpx;
	}

	.form-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;

		.form-item {
			margin-bottom: 30rpx;

			&.switch-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx 0;
			}

			.input-row {
				display: flex;
				align-items: center;

				.label {
					width: 160rpx;
					margin-bottom: 0;
					font-size: 28rpx;
					color: #333;
				}

				.input-wrapper {
					flex: 1;
					height: 80rpx;
					background-color: #F8F8F8;
					border-radius: 8rpx;
					padding: 0 20rpx;
					display: flex;
					align-items: center;

					input {
						width: 100%;
						height: 100%;
						font-size: 28rpx;
						background: transparent;
						border: none;
					}
				}
			}

			.label {
				display: block;
				font-size: 28rpx;
				color: #333;
				margin-bottom: 20rpx;
			}

			input,
			textarea {
				width: 100%;
				padding: 20rpx;
				border: 1rpx solid #eee;
				border-radius: 8rpx;
				font-size: 28rpx;

				&::placeholder {
					color: #999;
				}
			}

			textarea {
				height: 200rpx;
			}

			.word-count {
				font-size: 24rpx;
				color: #999;
				text-align: right;
				margin-top: 10rpx;
			}
		}

		.logo-upload {
			margin: 0 auto;
			width: 200rpx;
			height: 200rpx;
			border: 2rpx dashed #ddd;
			border-radius: 12rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin-bottom: 30rpx;

			.logo-preview {
				width: 100%;
				height: 100%;
				border-radius: 12rpx;
			}

			.upload-placeholder {
				text-align: center;
				width: 100%;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;

				.upload-content {
					display: flex;
					flex-direction: column;
					align-items: center;
				}

				.icon {
					font-size: 48rpx;
					color: #999;
					margin-bottom: 10rpx;
					display: block;
				}

				.text {
					font-size: 24rpx;
					color: #999;
					display: block;
				}
			}
		}

		.radio-label {
			margin-right: 30rpx;
			font-size: 28rpx;
		}

		.tags-container {
			display: flex;
			flex-wrap: wrap;
			margin: 0 -10rpx;

			.tag {
				margin: 10rpx;
				padding: 10rpx 30rpx;
				background-color: #f5f5f5;
				border-radius: 30rpx;
				font-size: 26rpx;
				color: #666;

				&.active {
					background-color: #4CAF50;
					color: #fff;
				}
			}
		}

		.area-picker {
			display: flex;
			justify-content: space-between;
			margin-top: 10rpx;

			.picker-item {
				flex: 1;
				height: 80rpx;
				background-color: #F8F8F8;
				border-radius: 8rpx;
				margin: 0 10rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				color: #333;

				&:first-child {
					margin-left: 0;
				}

				&:last-child {
					margin-right: 0;
				}

				text {
					color: #999;
				}
			}
		}
	}

	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx;
		background-color: #fff;

		.create-btn {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			background-color: #4CAF50;
			color: #fff;
			border-radius: 40rpx;
			font-size: 32rpx;
		}
	}
</style>